package hn.cch.advanced.concurrent.atomic;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.Unsafe;


import java.lang.reflect.Field;

public class UnsafeDemo {

    private static final Logger logger = LoggerFactory.getLogger(UnsafeDemo.class);

    private volatile String string;

    public String getString() {
        return string;
    }

    public void setString(String string) {
        this.string = string;
    }

    /**
     * 只能通过反射获得Unsafe对象
     *
     * @return Unsafe对象
     */
    public static Unsafe getUnsafe() {
        Unsafe unsafe = null;
        try {
            Field theUnsafe = Unsafe.class.getDeclaredField("theUnsafe");
            theUnsafe.setAccessible(true);
            unsafe = (Unsafe) theUnsafe.get(null);
        } catch (Exception e) {
            logger.error(e.getMessage());
        }
        return unsafe;
    }

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {

        Unsafe unsafe = UnsafeDemo.getUnsafe();
        String str = "str";
        String string = "string";
        Field field = UnsafeDemo.class.getDeclaredField("string");
        long offset = unsafe.objectFieldOffset(field);// 对象属性的偏移量

        UnsafeDemo demo = new UnsafeDemo();
        demo.setString(string);
        // 使用CAS操作对象属性
        logger.debug("compareAndSwapObject:{}", unsafe.compareAndSwapObject(demo, offset, string, str));
        logger.debug("string:{}", demo.getString());

    }


}
